package com.singerw.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.singerw.mapper.TwOptionsMapper;
import com.singerw.pojo.TwOptions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version V1.0
 * @Package com.singerw.service
 * @auhter 张欣
 * @date 2021/1/3-7:30 PM
 */

@Service
public class TwOptionsService {

    @Resource
    private TwOptionsMapper twOptionsMapper;

    public TwOptions findByName(String name) {
        QueryWrapper<TwOptions> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        List<TwOptions> twOptions = twOptionsMapper.selectList(wrapper);
        if(twOptions.size() == 0){
            return null;
        }
        return twOptions.get(0);
    }

    public void save(TwOptions twOptions) {
        TwOptions byKey = findByName(twOptions.getName());
        if (byKey == null) {
            twOptionsMapper.insert(twOptions);
            return;
        }
        byKey.setValue(twOptions.getValue());
        UpdateWrapper<TwOptions> wrapper = new UpdateWrapper<>();
        wrapper.eq("name", byKey.getName());
        twOptionsMapper.update(byKey,wrapper);
    }

    public void remove(String name){
        QueryWrapper<TwOptions> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        twOptionsMapper.delete(wrapper);
    }

    public JSONObject getRoutineSettings(){
        TwOptions routine = findByName("routine");
        return JSON.parseObject(routine.getValue());
    }

}
